/*
 * Copyright 2009 Armando Blancas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package tests.taskgraph.tasks.io;

import java.beans.PropertyEditor;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import junit.framework.Assert;
import junit.framework.JUnit4TestAdapter;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import taskgraph.channels.Channel;
import taskgraph.ports.InputPort;
import taskgraph.ports.OutputPort;
import taskgraph.reflect.Field;
import taskgraph.reflect.SqlDateEditor;
import taskgraph.reflect.SqlTimeEditor;
import taskgraph.reflect.SqlTimestampEditor;
import taskgraph.tasks.io.ReadDelimitedTextFile;

public class ReadDelimitedTextFileTest {

	/**
	 * Runs the test suite in this class from the command line.
	 * 
	 * @param args	Arguments are ignored.
	 */
	public static void main(String[] args) {
		org.junit.runner.JUnitCore.runClasses(ReadDelimitedTextFileTest.class);
	}
	
	/**
	 * Provides compatibility with 3.x versions of JUnit.
	 * 
	 * @return A 3.x-compatible test suite.
	 */
	public static junit.framework.Test suite() {
		return new JUnit4TestAdapter(ReadDelimitedTextFileTest.class);
	}
	
	/**
	 * For reading fields #2 and #6 (start @ 1) from Customers.txt 
	 */
	public static class Balance {
		private String name;
		private double balance;
		
		/**
		 * Required default constructor.
		 */
		public Balance() {
			// do nothing
		}

		public Balance(String name, double balance) {
			setName(name); 
			setBalance(balance); 
		}
		
		@Field(position=2)
		public String getName () { return name; }
		public void setName(String name) { this.name = name; }
		
		@Field(position=6)
		public double getBalance() { return balance; }
		public void setBalance(double balance) { this.balance = balance; }
	}
	
	private OutputPort<Customer> output;
	
	@Before
	public void setup() {
		Channel<Customer> channel = new Channel<Customer>();
		output = channel.getOutputPort();
	}
	
	@After
	public void cleanup() {
		output.close();
	}
	
    /*+----------------------------------------------------------------------+
	  |                                                                      | 
	  | Test the constructors.                                               | 
	  |                                                                      | 
	  +----------------------------------------------------------------------+*/
	
	@Test
	public void defaultConstructor() {
		ReadDelimitedTextFile<Customer> task = 
			new ReadDelimitedTextFile<Customer>();
		
		Assert.assertNotNull(task);
	}
	
	@Test
	public void defaultInstanceClass() {
		ReadDelimitedTextFile<Customer> task = 
			new ReadDelimitedTextFile<Customer>();
		
		Assert.assertEquals(
			ReadDelimitedTextFile.class, task.getClass());
	}

	@Test
	public void constructorWithArgs() {
		ReadDelimitedTextFile<Customer> task = 
			new ReadDelimitedTextFile<Customer>(
				output, Customer.class, "filename");
		
		Assert.assertNotNull(task);
	}
	
	@Test
	public void instanceClassWithArgs() {
		ReadDelimitedTextFile<Customer> task = 
			new ReadDelimitedTextFile<Customer>(
				output, Customer.class, "filename");
		
		Assert.assertEquals(
			ReadDelimitedTextFile.class, task.getClass());
	}

	@Test
	public void constructorWithFullArgs() throws UnsupportedEncodingException {
		ReadDelimitedTextFile<Customer> task = 
			new ReadDelimitedTextFile<Customer>(
				output, Customer.class, "filename", "US-ASCII", ',', '"');
		
		Assert.assertNotNull(task);
	}
	
	@Test
	public void instanceClassWithFullArgs() throws UnsupportedEncodingException {
		ReadDelimitedTextFile<Customer> task = 
			new ReadDelimitedTextFile<Customer>(
				output, Customer.class, "filename", "US-ASCII", ',', '"');
		
		Assert.assertEquals(
			ReadDelimitedTextFile.class, task.getClass());
	}

    /*+----------------------------------------------------------------------+
	  |                                                                      | 
	  | Test the run method with:                                            | 
	  |     Class: Customers.java                                            | 
	  |     File:  Customers.txt                                             | 
	  |                                                                      | 
	  +----------------------------------------------------------------------+*/
	
	@Test
	public void testRunWithCustomer() throws IOException, ParseException {
		DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
		Customer expected = new Customer(
			100L, "Donald", "Knuth", 'E', df.parse("04/12/1950"), 30.00);

		String filename = "tests-src/tests/taskgraph/tasks/io/customers.txt";

		Channel<Customer> ch = new Channel<Customer>();
		ReadDelimitedTextFile<Customer> task = 
			new ReadDelimitedTextFile<Customer>(
				ch.getOutputPort(), Customer.class, 
				filename, "US-ASCII", ',', '"');
		
		task.run();

		InputPort<Customer> input = ch.getInputPort();		
		Customer actual = input.read();
		input.close();

		Assert.assertEquals(expected.getId(), actual.getId());
		Assert.assertEquals(expected.getFirstName(), actual.getFirstName());
		Assert.assertEquals(expected.getLastName(), actual.getLastName());
		Assert.assertEquals(expected.getMiddleInitial(), actual.getMiddleInitial());
		Assert.assertEquals(expected.getDob(), actual.getDob());
		Assert.assertEquals(expected.getBalance(), actual.getBalance());		
	}

    /*+----------------------------------------------------------------------+
	  |                                                                      | 
	  | Test the run method with:                                            | 
	  |     Class: Balance.java                                              | 
	  |     File:  Customers.txt                                             | 
	  |                                                                      | 
	  +----------------------------------------------------------------------+*/
	
	@Test
	public void testRunWithBalance() throws IOException, ParseException {		
		Balance expected = new Balance("Donald", 30.00);
		String filename = "tests-src/tests/taskgraph/tasks/io/customers.txt";

		Channel<Balance> ch = new Channel<Balance>();
		ReadDelimitedTextFile<Balance> task = 
			new ReadDelimitedTextFile<Balance>(
				ch.getOutputPort(), Balance.class, 
				filename, "US-ASCII", ',', '"');
		
		task.run();

		InputPort<Balance> input = ch.getInputPort();		
		Balance actual = input.read();
		input.close();

		Assert.assertEquals(expected.getName(), actual.getName());
		Assert.assertEquals(expected.getBalance(), actual.getBalance());		
	}

    /*+----------------------------------------------------------------------+
	  |                                                                      | 
	  | Test the run method with:                                            | 
	  |     Class: SupportedTypes.java                                       | 
	  |     File:  supported-types.txt                                       | 
	  |                                                                      | 
	  +----------------------------------------------------------------------+*/

	@Test
	public void testRunWithSupportedTypes() throws IOException, ParseException {
		DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
		java.util.Date date = df.parse("01/31/2009");
		
		PropertyEditor editor = new SqlDateEditor();
		editor.setAsText("2009-01-01");
		java.sql.Date sqldate = (java.sql.Date) editor.getValue();
		
		editor = new SqlTimeEditor();
		editor.setAsText("08:30:45");
		java.sql.Time time = (java.sql.Time) editor.getValue();
		
		editor = new SqlTimestampEditor();
		editor.setAsText("2009-01-01 08:30:45");
		java.sql.Timestamp tstamp = (java.sql.Timestamp) editor.getValue();
		
		SupportedTypes expected = new SupportedTypes(true, (byte) 127, '@', 
			(short) 5005, 50000, 1700500111L, 3.1416F, 0.333333333333, 
			"Now is the time.", new BigInteger("1234567890000000"), 
			new BigDecimal("1000000000005000111"), date, sqldate, time, tstamp,   
		    Boolean.FALSE, Byte.valueOf((byte)32), Character.valueOf('#'), 
		    Short.valueOf((short)2001), Integer.valueOf(102001), 
		    Long.valueOf(1200000000L), Float.valueOf(1.995f), 
		    Double.valueOf(2.322334500));
		
		String filename = "tests-src/tests/taskgraph/tasks/io/supported-types.txt";

		Channel<SupportedTypes> ch = new Channel<SupportedTypes>();
		ReadDelimitedTextFile<SupportedTypes> task = 
			new ReadDelimitedTextFile<SupportedTypes>(
				ch.getOutputPort(), SupportedTypes.class, 
				filename, "US-ASCII", ',', '"');
		
		task.run();

		InputPort<SupportedTypes> input = ch.getInputPort();		
		SupportedTypes actual = input.read();		
		input.close();
		
		Assert.assertEquals(expected.isBooleanValue(), actual.isBooleanValue());
		Assert.assertEquals(expected.getByteValue(), actual.getByteValue());
		Assert.assertEquals(expected.getCharValue(), actual.getCharValue());
		Assert.assertEquals(expected.getShortValue(), actual.getShortValue());
		Assert.assertEquals(expected.getIntValue(), actual.getIntValue());
		Assert.assertEquals(expected.getLongValue(), actual.getLongValue());
		Assert.assertEquals(expected.getFloatValue(), actual.getFloatValue());
		Assert.assertEquals(expected.getDoubleValue(), actual.getDoubleValue());
		Assert.assertEquals(expected.getStringValue(), actual.getStringValue());
		
		Assert.assertEquals(expected.getBigIntValue(), actual.getBigIntValue());
		Assert.assertEquals(expected.getBigDecimalValue(), actual.getBigDecimalValue());
		Assert.assertEquals(expected.getDateValue(), actual.getDateValue());
		Assert.assertEquals(expected.getSqlDateValue(), actual.getSqlDateValue());
		Assert.assertEquals(expected.getTimeValue(), actual.getTimeValue());
		Assert.assertEquals(expected.getTstampValue(), actual.getTstampValue());
		
		Assert.assertEquals(expected.getBooleanWrapper().booleanValue(), actual.getBooleanWrapper().booleanValue());
		Assert.assertEquals(expected.getByteWrapper().byteValue(), actual.getByteWrapper().byteValue());
		Assert.assertEquals(expected.getCharWrapper().charValue(), actual.getCharWrapper().charValue());
		Assert.assertEquals(expected.getIntWrapper().intValue(), actual.getIntWrapper().intValue());
		Assert.assertEquals(expected.getLongWrapper().longValue(), actual.getLongWrapper().longValue());
		Assert.assertEquals(expected.getFloatWrapper().floatValue(), actual.getFloatWrapper().floatValue());
		Assert.assertEquals(expected.getDoubleWrapper().doubleValue(), actual.getDoubleWrapper().doubleValue());
	}

    /*+----------------------------------------------------------------------+
	  |                                                                      | 
	  | Negative tests for constructors.                                     | 
	  |                                                                      | 
	  +----------------------------------------------------------------------+*/

	@Test(expected=IllegalArgumentException.class)
	public void constructorWithNullOutputPort() throws IOException {
		new ReadDelimitedTextFile<Customer>(null, Customer.class, "filename");
	}

	@Test(expected=IllegalArgumentException.class)
	public void constructorWithNullClazz() throws IOException {
		new ReadDelimitedTextFile<Customer>(output, null, "filename");
	}

	@Test(expected=IllegalArgumentException.class)
	public void constructorWithNullFilename() throws IOException {
		new ReadDelimitedTextFile<Customer>(output, Customer.class, null);
	}

	@Test(expected=IllegalArgumentException.class)
	public void constructorWithNullCharsetName() throws UnsupportedEncodingException {
		new ReadDelimitedTextFile<Customer>(output, Customer.class, "Filename", null, '|', '@');
	}

	@Test(expected=UnsupportedEncodingException.class)
	public void constructorWithBadCharsetName() throws UnsupportedEncodingException {
		new ReadDelimitedTextFile<Customer>(output, Customer.class, "Filename", "NAVAJO", '|', '@');
	}

    /*+----------------------------------------------------------------------+
	  |                                                                      | 
	  | Negative tests.                                                      | 
	  |                                                                      | 
	  +----------------------------------------------------------------------+*/

}
